<?php

class proving {
	
	public $regulars = array(
		'username'=>'/^([a-zA-Z0-9]|[._]){3,20}$/',
		'password'=>'/^(\w){3,20}$/',
		'tenant_name'=>'/^[\x{4e00}-\x{9fa5}\w\.\s]{2,20}$/u',//验证商户名称
		//'m'=>'/^13[0-9]{9}$|14[0-9]{9}|15[0-9]{9}$|18[0-9]{9}|17[0-9]{9}$/',//手机号码
		'm'=>'/^13[0-9]{9}$|14[0-9]{9}$|15[0-9]{9}$|18[0-9]{9}$|17[0-9]{9}$/',//手机号码
		'e'=>"/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/",//验证邮箱
		's'=>'/^[\x{4e00}-\x{9fa5}\w\.\s]+$/u',//不可输入特殊字符
		'x'=>'/^[0-9]+([.]{1}[0-9]{1,2})?$/',  //验证金额有小数点
		'n'=>'/^\d+$/',//验证数字	
		'7'=>'/^\d{7}$/',//验证七位数字 扣单号 先行登记号用
		'8'=>'/^\d{8}$/',//验证8位数字 卷烟代码用
		'tel'=>'/1[3857]{1}[1235689]{1}\d{8}|15[1235689]\d{8}|188\d{8}/',//支持手机号码
		'ip'=>'/^(2[5][0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})$/',			'd'=>'/^^\d{1,5}$/'
    );
					
	public $error = '';
	
	//自动加载
	public function __construct(){
		
	}
	
	//验证
	public function regular($key,$value){
		if(!@$this->regulars[$key]){
			if(!preg_match($key,$value)){
				return false;
			}
		} else {
			if(!preg_match($this->regulars[$key],$value)){
				return false;
			}
		}
		
		return true;
		
	}
	
	//数组转json
	public function arrayTOjson($array){
		$array = $this->objectToArrayU($array);
		return json_encode($array);	
	}
	
	//数组转json
	public function arrayTOjson2($array){
		$array = $this->objectToArrayU2($array);
		return urldecode(json_encode($array));	
	}
	
	//对象转数组
	public function objectToArray($data){
		
		if(is_object($data)){
			$data = (array)$data;	
		}
		if($data){
		foreach($data as $key=>$value){
			if(is_object($value)){
				$data[$key] = $this->objectToArray($value);	
			}	
		}
		}
		return $data;	
	}
	
	public function my_iconv($data){
		$encode = mb_detect_encoding($data, array("ASCII","UTF-8","GB2312","GBK","BIG5")); 
		if ($encode == "UTF-8"){ 
			//return 	@iconv('utf-8','gb2312//IGNORE',$data);

			return 	@iconv('utf-8','GBK//IGNORE',$data);

		} else {
			return $data;	
		}
	}
	
	public function my_iconv_h($data){
		$encode = mb_detect_encoding($data, array("ASCII","UTF-8","GB2312","GBK","BIG5")); 
 
		return 	@iconv($encode,'utf-8',$data);

	}
	
	//对象转数组,并URL编码
	public function objectToArrayU($data){
		
		if(is_object($data)){
			$data = (array)$data;	
		}
		
		foreach($data as $key=>$value){
			if(is_object($value) || is_array($value)){
				$data[$key] = $this->objectToArrayU($value);		
			} /*else {
				$data[$key] = @iconv('gb2312','utf-8',$value);
			}*/
		}
		
		return $data;	
	}
	
	//对象转数组,并URL编码
	public function objectToArrayU2($data){
		
		if(is_object($data)){
			$data = (array)$data;	
		}
		
		foreach($data as $key=>$value){
			if(is_object($value) || is_array($value)){
				$data[$key] = $this->objectToArrayU2($value);		
			} else {
				$data[$key] = @iconv('gb2312','utf-8',$value);
				$data[$key] = urlencode($data[$key]);	
			}
		}
		
		return $data;	
	}
	
	//对象转数组且设置键值
	public function objectToArrayK($data,$keys,$KeyV=NULL,$type=false){
		
		$array = array();
		
		if(is_object($data)){
			$data = (array)$data;	
		}
		
		foreach($data as $key=>$value){
			if(is_object($value) || is_array($value)){
				
				if(is_object($value)){$ds = (array)$value;} else {$ds = $value;};
				
				if(array_key_exists($keys, $ds)){
					
					if($type == false){
						
						$array[$ds[$keys]][] = $this->objectToArray($value);
					
					} else {
						$Arrays = $this->objectToArray($value);
						$Arrays['md5'] = md5($Arrays[$KeyV]);
						$array[md5($Arrays[$keys])][] = $Arrays;
					}
					
					
				} else {
					$array[$key] = $this->objectToArray($value);	
				}
			} else {
				$array[$key] = 	$value;
			}
		}
		
		return $array;	
	}
	
	//对象转数组且设置键值
	public function objectToArrayK2($data,$keys){
		
		$array = array();
		
		if(is_object($data)){
			$data = (array)$data;	
		}
		
		foreach($data as $key=>$value){
			if(is_object($value) || is_array($value)){
				
				if(is_object($value)){$ds = (array)$value;} else {$ds = $value;};
				
				if(array_key_exists($keys, $ds)){
					$array[$ds[$keys]] = $this->objectToArray($value);	
				} else {
					$array[$key] = $this->objectToArray($value);	
				}
			} else {
				$array[$key] = 	$value;
			}
		}
		
		return $array;	
	}
	

	//验证是否登录
	public function isLogin(){
		if(empty($_COOKIE['user_id']) || !isset($_COOKIE['username'])){
			header('location:index-login');
			exit;
			return false;
		}
	}
	
	//验证是否登录
	public function isLogin2($authority){

		if(!isset($_COOKIE['userid'])){header('location:../user-login');exit;return false;}
		if(empty($_COOKIE['userid'])){header('location:../user-login');exit;return false;}
		
		if(!isset($_COOKIE['authority'])){header('location:../user-login');exit;return false;}

		if($_COOKIE['authority'] != 'all' && $authority != $_COOKIE['authority']){header('location:../user-no_auth');exit;return false;}
		
	}
	
	/*//获取是否存在某个权限并验证是否登陆
	public function auth($visit='',$power=true){
		if(!isset($_COOKIE['userid'])){header('location:./user-index');exit;return false;}
		if(empty($_COOKIE['userid'])){header('location:./user-index');exit;return false;}
		if($power == true){
			if(!$visit){header('location:./user-no_auth');exit;return false;}
			$auth = isset($_COOKIE['authority'])?$_COOKIE['authority']:'';
			if(strpos($auth,$visit) === false && $auth != 'all'){header('location:./user-no_auth');exit;return false;}
		}
		
	}*/
			//获取是否存在某个权限并验证是否登陆
	public function auth($visit='',$power=true){
		if(!isset($_COOKIE['userid'])){header('location:./user-index');exit;return false;}
		if(empty($_COOKIE['userid'])){header('location:./user-index');exit;return false;}
		if($power == true){
			
			$auth = isset($_COOKIE['authority'])?$_COOKIE['authority']:'';
			
			if(!$visit){
				if($auth == 'all'){
					return true;exit;	
				} else {
					header('location:./user-no_auth');exit;return false;
				}
			}
			if(strpos($auth,$visit) === false && $auth != 'all'){header('location:./user-no_auth');exit;return false;}
		}
		
	}

	
	//验证是否存在权限
	public function authX($authX){
		
		$auth = isset($_COOKIE['authority'])?$_COOKIE['authority']:'';
		
		if($auth == 'all'){
			return true;	
		}
		
		if(strpos($auth,$authX) === false){
			return false;	
		} else {
			return true;	
		}
	}
	
	
	//秒计算天、小时、分钟、秒
	public function humandate($time) {
		
		$date = '';
		
		$date .= '<span>'.floor($time / 86400).'</span> 天 ';
		$time = ($time%86400);
		
		$date .= '<span>'.floor($time / 3600).'</span> 小时 ';
		$time = ($time%3600);
		
		$date .= '<span>'.floor($time / 60).'</span> 分 ';
		$time = ($time%60);
		
		$date .= '<span>'.floor($time).'</span> 秒 ';
		
        return $date;
	}
	
	//秒计算天、小时、分钟、秒
	public function humandate2($time) {
		
		$date = '';
		
		$date .= floor($time / 86400).'天';
		$time = ($time%86400);
		
		$date .= floor($time / 3600).'小时';
		$time = ($time%3600);
		
		$date .= floor($time / 60).'分';
		$time = ($time%60);
		
		$date .= floor($time).'秒';
		
        return $date;
	}
	//秒计算天、小时、分钟、秒拆分
	public function humandate3($time) {
		
		$date = '';
		
		$date = floor($time / 86400);
		$time = ($time%86400);
		
		$date1 = floor($time / 3600);
		$time = ($time%3600);
		
		$date2 = floor($time / 60);
		$time = ($time%60);
		
		$date3 = floor($time);
		$array=array('d'=>$date,'m'=>$date1,'n'=>$date2,'s'=>$date3);
        return $array ;
	}


	public function info($name){
		return $name.' 您好，您的申请已经收到，近期办证人员将与您联系，请保持手机畅通。';	
	}

	/************************************************
	*设置为dhtmlXTree(树形菜单)需要json传格式
	*param  data为数据 key 为初始键值 
	*/
	public function tree($data,$key){
		$array = array('id'=>0);
		if($data){
		foreach($data[$key] as $K=>$value){
			
			$array['item'][$K]['id'] = $value['id'];
			$array['item'][$K]['text'] = $value['name'];

			if(array_key_exists($value['id'], $data)){
				
				foreach($data[$value['id']] as $KZ=>$V){
					
					$array['item'][$K]['item'][$KZ]['id'] = $V['id'];
					$array['item'][$K]['item'][$KZ]['text'] = $V['name'];
						
				}

			}
			
		}	
		}
		return $this->arrayTOjson($array);
	}	
	
	//分割字符串
	public function substrA($code,$array=array()){
		$arrays = array();
		foreach($array as $key=>$value){
			$arrays[] = substr($code,$value['start'],$value['end']);	
		}
		
		return $arrays;
		
	}
	
	
	//某个时间加N天，只计算工作日
	public function workDay($time,$day){

		$Dtime = strtotime('+'.$day.' days',$time);
		
		$days = $day;
		$times = $time;
		$date = time();
		
		$Wd = 0;
		while($times<=$date) {
		 $week = date('w',$times);
		 
		 if($week == 0 || $week == 6){
			$Wd += 86400;
		 }
		  $times = $times+86400;
		}
		$Dtime += $Wd;
		
		
		if(date('w',$date) == 6 || date('w',$date) == 0){
			
			$Dtime = $Dtime	+ ($date - strtotime(date('Y-m-d 00:00:00',$date)));
		}
		$m = $Dtime-$date;
		if($m < 0)$m = 0;
		
		return $m;
	}
	
	//某个时间加N天，只计算工作日
	public function workDate($time,$day){

		$week = date('w',$time);
		
		$days = $day;
		
		if($week == 0){
			
		} else if($week == 6){
			$time = strtotime("+1 day",$time);//星期六加上2		
		}else {
			$days = $day - (5-$week);
			$time = ($days >= 0)?strtotime("+".(5-$week+2)." day",$time):strtotime("+".$day." day",$time);
		}
		if($days != 5){
			$Wday = intval($days/5);;
			$days = ($Wday*2)+$days;
		
		}
		
		if($days < 0){
			$days = 0;
		}

		return strtotime('+'.$days.' days',$time);
	}
	
	
	public function crType($type){
		
		$a = array(
					'1'	=>	'入库',
					'2'	=>	'罚没',
					'3'	=> '送检',
					'4' => '销毁',
                	'5' =>'返还',
               		'6' =>'其他',
               		'7' =>'移交',
					'8' =>'委托销毁',
               		'9' =>'移送司法机关',
					'10'=>'委托送检',
				);
					
		return @$a[$type];
	}
	
	public function crRe($type){
		
		$a = array(
					'1'	=>	'暂扣区',
					'2'	=>	'罚没区',
					'3'	=>	'移交区'
				);
					
		return @$a[$type];
	}
	
	/**
	 * 
	 * 生成唯一订单号
	 * @return 产生的订单号
	 */
	public function out_trade_no(){
		return date('YmdHis').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);		
	}

	/**
	 * 
	 * php获取不带后缀的文件名
	 * @return 不带后缀的文件名
	 */
	public function noExtName($fileName){
		$result = substr($fileName,0,strrpos($fileName,'.'));
		return 	$result; 
	}
	
	/**
	 * 
	 * php获取文件扩展名
	 * @return 文件扩展名
	 */
	function get_extension($file){
		$ext = substr(strrchr($file, '.'), 1);
		return $ext;
	} 
	
	/*
	 * 判断Url是否为真实有效的url
	 * 王二凯
	 * 2016-11-15 15：08
	 */
	public function getHeaders($url){
		$headers=@get_headers($url);//抓取HTTP Header information 
		if(strpos($headers[0],'404')===false){//检查看看有没有404啊 
			return true; 
		}else{ 
			return false; 
		}
	}
	
	/*
	 * 参数加密校验
	 * 史立鑫
	 * 2017-10-17
	 */
	public function check_app_url_v1($check_app_secret,$check_data = 1){
	    $http_time = isset($_REQUEST['http_time'])?$_REQUEST['http_time']:'';
	    $checksum = isset($_REQUEST['checksum'])?$_REQUEST['checksum']:'';
	    $AppKey = isset($_REQUEST['AppKey'])?$_REQUEST['AppKey']:'';
	    $app_data = isset($_REQUEST['http_data'])?$_REQUEST['http_data'] : '{}';  

    	if($check_data == 2){
    		return json_decode($app_data,true);
    	}
	    
		
	    // a($_REQUEST);exit;
        if(!$checksum or !$http_time){
            $code = '1002';
            $msg = '请求无效';
            $return = array('code'=>$code,'message'=>$msg);
            echo json_encode($return);exit;
        }
        // a(123);
        //判断数据是否正确
        
        $app_data = stripcslashes($app_data);//去掉转义符

		if(is_null(json_decode($app_data))){
			echo json_encode(array('code'=>1004,'message'=>'内容格式不是json'));exit; 
		}
        
       if(time() - $http_time > 600){
            $code = '1002';
            $msg = '请求过期';
            $return = array('code'=>$code,'message'=>$msg);
            echo json_encode($return);exit;
        }
        
		$app_data_a = urlencode($app_data);		//加密前先转码
        $sha1 = sha1($check_app_secret.md5($app_data_a).$http_time);		//拼接加密串
		
        if($sha1 != $checksum){
            $code = '1003';
            $msg = '秘钥错误';
            $return = array('code'=>$code,'message'=>$msg);
            echo json_encode($return);exit;
        }

        //返回所需数据
		$data = json_decode($app_data,true);
		
		//特殊字符转码
		foreach($data as $k => $v){
			$data[$k] = urldecode($v);
		}
		
		if($check_data){
		    
    		$version = isset($data['version']) ? $data['version']:'';//版本号
    		$imei    = isset($data['imei']) ? $data['imei']:'';//串号
    		$session = isset($data['session']) ? $data['session']:'';//session会话
    		
    		if(!$version or !$imei or !$session){
                $code = '1005';
                $msg = '缺少必要参数';
                $return = array('code'=>$code,'message'=>$msg);
                echo json_encode($return);exit;
            }
    		
        }
        
        return $data;

	}
	
	//返回错误信息
	public function error_info($code,$msg){
	    $return = array('code'=>$code,'message'=>$msg);
        echo json_encode($return);exit;
	}
	
	//返回成功信息
	public function success_info($msg,$data){
	    $return = array('code'=>'200','message'=>$msg,'data'=>$data);
        echo json_encode($return);
	}


	/** 
	* @desc curl抓取类 
	* @param $url 抓取地址 
	* @param $request 请求类型 GET POST 
	* @param $data 需发送的数据 
	* @param $head 是否显示头信息 TRUE FALSE 
	* @param $cookies 获取cookies 1 传递cookies文件 2 保存cookies文件 
	* @return String 
	* @date 2017-05-22 
	*/  
	public function curl( $url, $request = 'GET', $data = NULL, $head = FALSE, $cookies = FALSE, $header = NULL, $timeout = 600 ){
	    
	    if($cookies == 1 or $cookies == 2){
	        //创建cookie文件
            if(isset($_COOKIE['PHPSESSID'])){
                 $ip_number = $_COOKIE['PHPSESSID'];
            }else{
                $ip = $this->get_proxy_ip();
                $ip_number = str_replace('.','_',$ip);
            }
            
            $cookie_url = dirname(__FILE__)."/../../theme/cookie/";
            
            if (!is_dir($cookie_url)){
                //当路径不穿在
                mkdir($cookie_url,0777,1);//创建路径
            }
            
            $cookie_file = $cookie_url.$ip_number.'.txt';
            if(!file_exists($cookie_file)){
            	$fp=fopen($cookie_file,"w+"); 
            	fwrite($fp,""); 
            	fclose($fp); 
            }
            
    		$this->cookies_file = $cookie_file;
	    }
	    
	    //$this->cookies_file = dirname(__FILE__)."/../../theme/cookie/cookie";  
	      
	    $ssl = substr($url, 0, 8) == "https://" ? TRUE : FALSE;//验证是否是https请求  
	      
	    $ch = curl_init();
	      
	    curl_setopt($ch, CURLOPT_URL, $url);
	      
	    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);    
	      
	    if( $head === TRUE ) {  
	        curl_setopt($ch, CURLOPT_HEADER, TRUE);//获取消息头  
	    }  
	      
	    if(is_array($header)){          //发送头信息  
	        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);  
	    }  
	      
	    //https请求  
	    if($ssl === TRUE) {  
	        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); //信任任何证书  
	      
	        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); //不检查证书中是否设置域名    
	    }  
	      
	     curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);//设置不自动显示内容    
	      
	    //POST请求  
	    if($request == 'POST') {  
	          
	        curl_setopt($ch, CURLOPT_POST, TRUE);   
	          
	        is_array($data) && $data = http_build_query($data);  
	        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);    
	    }  
	      
	    //保存cookies  
	    if($cookies == 2) {  
	        curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookies_file );  
	    }  
	      
	    //需传递COOKIE文件  
	    if($cookies == 1) {  
	        curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookies_file );  
	    }  
	      
	    $return = curl_exec($ch);  
	      
	    if( $error = curl_error($ch) ) {  
	        // throw new \Exception($error);  
	    }  
	      
	    curl_close($ch);   
	    return $return;      
	      
	}
	
	//获取客户端真实ip
	public function get_proxy_ip(){
        $arr_ip_header = array(
            'HTTP_CDN_SRC_IP',
            'HTTP_PROXY_CLIENT_IP',
            'HTTP_WL_PROXY_CLIENT_IP',
            'HTTP_CLIENT_IP',
            'HTTP_X_FORWARDED_FOR',
            'REMOTE_ADDR',
        );
        $client_ip = 'unknown';
        foreach ($arr_ip_header as $key){
            if (!empty($_SERVER[$key]) && strtolower($_SERVER[$key]) != 'unknown'){
                $client_ip = $_SERVER[$key];
                break;
            }
        }
        return $client_ip;
    }


	public function curl_file_upload($url,$path,$fileName){
		@define('BASE_PATH',str_replace('\\','/',realpath(dirname(__FILE__).'/../../'))."/");	//获取项目根目录
        //创建cookie文件
        
        if(isset($_COOKIE['PHPSESSID'])){
            $ip_number = $_COOKIE['PHPSESSID'];
        }else{
            $ip = $this->get_proxy_ip();
            $ip_number = str_replace('.','_',$ip);
        }
	    
        
        $cookie_url = dirname(__FILE__)."/../../theme/cookie/";
        
        if (!is_dir($cookie_url)){
            //当路径不穿在
            mkdir($cookie_url,0777,1);//创建路径
        }
        
        $cookie_file = $cookie_url.$ip_number.'.txt';
        if(!file_exists($cookie_file)){
        	$fp=fopen($cookie_file,"w+"); 
        	fwrite($fp,""); 
        	fclose($fp); 
        }
        
		$this->cookies_pic = $cookie_file;
    	
		//$this->cookies_file = dirname(__FILE__)."/../../theme/cookie/cookie";  	//cookie文件目录
		
		$path = str_replace('\\','/',BASE_PATH.$path);
		
		$ch = curl_init(); 
		if (defined('CURLOPT_SAFE_UPLOAD')) {
			curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
		}
		
		$data = array('fileUrl' => '@' . $path,'fileName'=>$fileName);//‘@’ 符号告诉服务器为上传资源
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POST, 1 );
		curl_setopt($ch, CURLOPT_TIMEOUT, 600);    
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_USERAGENT,"TEST");
		curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookies_pic );  
		$result = curl_exec($ch);
		$error = curl_error($ch);
		
		if(!$error){
			return json_decode($result);
		}else{
			return false;
		}
		
	}
	
}










